package logic

import (
	"context"
	"errors"
	"login-hub/model/cache"
	"login-hub/model/mysql"

	"login-hub/loginrpc/internal/svc"
	"login-hub/loginrpc/loginrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *loginrpc.LoginRequest) (*loginrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("tel = ?", in.Tel).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("当前账号不存在，请更换")
	}

	if user.Password != in.Password {
		return nil, errors.New("密码错误")
	}

	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Tel).Result()
	if result != in.SendSms {
		return nil, errors.New("验证码错误")
	}

	return &loginrpc.LoginResponse{
		UId: int64(user.ID),
	}, nil
}
